import {GenerDevelopFrm} from './FrmDevelop.js';
import {GenerFoolFrm} from './FrmFool.js';
import {GenerFreeFrm} from './FrmFree.js';
import {GenerCheckNames,checkBlanks,checkReg,validate} from './tools.js';
import $ from 'jquery'

//定义全局的MyFlowGener.vue的组件
let _this;

/**
 * 获取表单数据
 */
function GenerWorkNode(obj){
    _this = obj;
    let handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    handler.AddJson(_this.params);
    let data = handler.DoMethodReturnString("GenerWorkNode");
    if (data.indexOf('err@') == 0) {
        console.log(data);
        _this.$alert("获取表单数据失败,请查看控制台日志,或者联系管理员.", {
            dangerouslyUseHTMLString: true
        });
        return;
    }
    try {
        _this.flowData = JSON.parse(data);
    } catch (err) {
        console.log(data);
        _this.$alert(" GenerWorkNode转换JSON失败,请查看控制台日志,或者联系管理员.", {
            dangerouslyUseHTMLString: true
        });
        return;
    }
    _this.node = _this.flowData.WF_Node[0];
    //2.消息提醒，会签信息，退回信息
    let alertMsgEle="";
    let title="";
    let count=1;
    _this.flowData.AlertMsg.forEach(alertMsg=>{
        let _html ='<div>';
        _html +='<span class="titleAlertSpan"> ' + (count++) + "&nbsp;&nbsp;&nbsp;" + alertMsg.Title + '</span>';
        _html +='<div>' + alertMsg.Msg + '</div>';
        _html +='</div>';
        alertMsgEle += _html;
        title = alertMsg.Title;
    });

    if (_this.flowData.AlertMsg.length != 0 ) {
        _this.$alert(alertMsgEle, title, {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true

        });
    }

    if (_this.FormType === 11) {
        //获得配置信息.
        var frmNode = _this.flowData["FrmNode"];
        if (frmNode) {
            frmNode = frmNode[0];
            if (frmNode.FrmSln == 1)
                _this.$route.params.IsReadonly = 1
        }
    }
    //判断类型不同的类型不同的解析表单. 处理中间部分的表单展示.

    if (_this.node.FormType === 5) {
        //GenerTreeFrm(flowData); /*树形表单*/
        return;
    }

    if (_this.node.FormType === 0 || _this.node.FormType === 10) {
        GenerFoolFrm(obj); //傻瓜表单.
    }

    if (_this.node.FormType === 1) {
        GenerFreeFrm(obj);  //自由表单.
    }

    if (_this.node.FormType === 12)
        GenerDevelopFrm(obj);

    //2018.1.1 新增加的类型, 流程独立表单， 为了方便期间都按照自由表单计算了.
    if (_this.node.FormType === 11) {
        if (_this.flowData.FrmNode[0] != null && _this.flowData.FrmNode[0] != undefined)
            if (_this.flowData.FrmNode[0].FrmType == 0)
                GenerFoolFrm(obj); //傻瓜表单.
        if (_this.flowData.FrmNode[0].FrmType == 1)
            GenerFreeFrm(obj);
        if (_this.flowData.FrmNode[0].FrmType == 8)
            GenerDevelopFrm(obj);
    }

}


/**
 * 流程保存
 */
function Save(){
    //必填项和正则表达式检查
    var formCheckResult = true;

    if (checkBlanks() == false) {
        formCheckResult = false;
    }

    if (checkReg() == false) {
        formCheckResult = false;
    }

    if (formCheckResult == false) {
        return false;
    }

    //判断是否启用审核组件
    if(_this.node.FWCSta!=0){
        if(_this.$parent.$parent.$parent.WorkCheck_Save()==false)
            return false;
    }


    var params = getFormData(true, true,_this.$route.params);

    var handler = new _this.HttpHandler("BP.WF.HttpHandler.WF_MyFlow");
    $.each(params.split("&"), function (i, o) {
        var param = o.split("=");
        if (param.length == 2 && validate(param[1])) {
            handler.AddPara(param[0], param[1]);
        } else {
            handler.AddPara(param[0], "");
        }
    });
    var data = handler.DoMethodReturnString("Save"); //执行保存方法.

    //setToobarEnable();
    //刷新 从表的IFRAME
    var dtls = $('.Fdtl');
    $.each(dtls, function (i, dtl) {
        $(dtl).attr('src', $(dtl).attr('src'));
    });

    if (data.indexOf('保存成功') != 0 || data.indexOf('err@') == 0) {
        _this.$message({
            type: 'error',
            message: data
        });
        console.log(data);
    }
}

/**
 * 获取表单数据
 * @param {是否包含大文本} isCotainTextArea 
 * @param {是否包含路由参数} isCotainRouteParam 
 * @param {组件} route 
 */
function getFormData(isCotainTextArea, isCotainRouteParam,params) {
    var formss = $('form').serialize();

    var formArr = formss.split('&');
    var formArrResult = [];
    var haseExistStr = ",";
    var mcheckboxs = "";
    $.each(formArr, function (i, ele) {
        if (ele.split('=')[0].indexOf('CB_') == 0) {
            //如果ID获取不到值，Name获取到值为复选框多选
            var targetId = ele.split('=')[0];
            if ($('#' + targetId).length == 1) {
                if ($('#' + targetId + ':checked').length == 1) {
                    ele = targetId + '=1';
                } else {
                    ele = targetId + '=0';
                }
                formArrResult.push(ele);
            } else {

                if (mcheckboxs.indexOf(targetId + ",") == -1) {
                    mcheckboxs += targetId + ",";
                    var str = "";
                    $("input[name='" + targetId + "']:checked").each(function (index) {
                        if ($("input[name='" + targetId + "']:checked").length - 1 == index) {
                            str += $(this).val();
                        } else {
                            str += $(this).val() + ",";
                        }
                    });

                    formArrResult.push(targetId + '=' + str);
                }

               
            }

        }
        if (ele.split('=')[0].indexOf('DDL_') == 0) {

            var ctrlID = ele.split('=')[0];

            var item = $("#" + ctrlID).children('option:checked').text();

            var mystr = '';
            mystr = ctrlID.replace("DDL_", "TB_") + 'T=' + item;
            formArrResult.push(mystr);
            formArrResult.push(ele);
            haseExistStr += ctrlID.replace("DDL_", "TB_") + "T" + ",";
        }
        if (ele.split('=')[0].indexOf('RB_') == 0) {
            formArrResult.push(ele);
        }

    });
    $.each(formArr, function (i, ele) {
        var ctrID = ele.split('=')[0];
        if (ctrID.indexOf('TB_') == 0) {
            if (haseExistStr.indexOf(","+ctrID+",") == -1) {
                formArrResult.push(ele);
                haseExistStr += ctrID + ",";
            }
          
               
        }
    });

    //获取表单中禁用的表单元素的值
    var disabledEles = $('#divCCForm :disabled');
    $.each(disabledEles, function (i, disabledEle) {

        var name = $(disabledEle).attr('id');

        switch (disabledEle.tagName.toUpperCase()) {

            case "INPUT":
                switch (disabledEle.type.toUpperCase()) {
                    case "CHECKBOX": //复选框
                        formArrResult.push(name + '=' + encodeURIComponent(($(disabledEle).is(':checked') ? 1 : 0)));
                        break;
                    case "TEXT": //文本框
                    case "HIDDEN":
                        formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).val()));
                        break;
                    case "RADIO": //单选钮
                        name = $(disabledEle).attr('name');
                        var eleResult = name + '=' + $('[name="' + name + '"]:checked').val();
                        if ($.inArray(eleResult, formArrResult) == -1) {
                            formArrResult.push(eleResult);
                        }
                        break;
                }
                break;
            //下拉框            
            case "SELECT":
                formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).children('option:checked').val()));
                var tbID = name.replace("DDL_", "TB_") + 'T';
                if ($("#" + tbID).length == 1) {
                    if (haseExistStr.indexOf("," + tbID + ",") == -1) {
                        formArrResult.push(tbID + '=' + $(disabledEle).children('option:checked').text());
                        haseExistStr += tbID + ",";
                    }
                }
                break;

            //文本区域                    
            case "TEXTAREA":
                formArrResult.push(name + '=' + encodeURIComponent($(disabledEle).val()));
                break;
        }
    });

  

    if (!isCotainTextArea) {
        formArrResult = $.grep(formArrResult, function (value) {
            return value.split('=').length == 2 ? value.split('=')[1].length <= 50 : true;
        });
    }

    formss = formArrResult.join('&');
    var dataArr = [];
    //加上Route中的参数
    if (isCotainRouteParam) {
        var pageDataArr = [];
        for (var data in params) {
            pageDataArr.push(data + '=' + params[data]);
        }
        dataArr.push(pageDataArr.join('&'));
    }
    if (formss != '')
        dataArr.push(formss);
    var formData = dataArr.join('&');

    //为了复选框  合并一下值  复选框的值以  ，号分割
    //用& 符号截取数据
    var formDataArr = formData.split('&');

    var formDataResultObj = {};
    $.each(formDataArr, function (i, formDataObj) {
        //计算出等号的INDEX
        var indexOfEqual = formDataObj.indexOf('=');
        var objectKey = formDataObj.substr(0, indexOfEqual);
        var objectValue = formDataObj.substr(indexOfEqual + 1);
        if (formDataResultObj[objectKey] == undefined) {
            formDataResultObj[objectKey] = objectValue;
        } else {
            formDataResultObj[objectKey] = formDataResultObj[objectKey] + ',' + objectValue;
        }
    });

    var formdataResultStr = '';
    for (var ele in formDataResultObj) {
        formdataResultStr = formdataResultStr + ele + '=' + formDataResultObj[ele] + '&';
    }

    // 处理没有选择的文本框.
    //获得checkBoxNames 格式为: CB_IsXX,CB_IsYY,
    var ids = GenerCheckNames();

    if (ids) {
        var scores = ids.split(",");
        var arrLength = scores.length;
        for (var i = 0; i < arrLength; i++) {
            var field = scores[i];
            var index = formdataResultStr.indexOf(field);
            if (index == -1) {
                if ($("input[name='" + field + "'").length == 1)
                    formdataResultStr += '&' + field + '=0';
                else
                    formdataResultStr += '&' + field + '= ';
            }
        }
    }

    formdataResultStr = formdataResultStr.replace('&&', '&');

    return formdataResultStr;
}


export{
    GenerWorkNode,
    Save
};